<?php

/*
	[Discuz!] (C)2001-2007 Comsenz Inc.
	This is NOT a freeware, use is subject to license terms
    mark:has readed
	$Id: attachment.func.php 10115 2007-08-24 00:58:08Z cnteacher $
*/

if(!defined('IN_DISCUZ')) {
	exit('Access Denied');
}

function attachtype($type, $returnval = 'html') {

	static $attachicons = array(
			1 => 'common.gif',
			2 => 'binary.gif',
			3 => 'zip.gif',
			4 => 'rar.gif',
			5 => 'msoffice.gif',
			6 => 'text.gif',
			7 => 'html.gif',
			8 => 'real.gif',
			9 => 'av.gif',
			10 => 'flash.gif',
			11 => 'image.gif',
			12 => 'pdf.gif',
			13 => 'torrent.gif'
		);

	if(is_numeric($type)) {
		$typeid = $type;
	} else {
		if(preg_match("/bittorrent|^torrent\t/", $type)) {
			$typeid = 13;
		} elseif(preg_match("/pdf|^pdf\t/", $type)) {
			$typeid = 12;
		} elseif(preg_match("/image|^(jpg|gif|png|bmp)\t/", $type)) {
			$typeid = 11;
		} elseif(preg_match("/flash|^(swf|fla|swi)\t/", $type)) {
			$typeid = 10;
		} elseif(preg_match("/audio|video|^(wav|mid|mp3|m3u|wma|asf|asx|vqf|mpg|mpeg|avi|wmv)\t/", $type)) {
			$typeid = 9;
		} elseif(preg_match("/real|^(ra|rm|rv)\t/", $type)) {
			$typeid = 8;
		} elseif(preg_match("/htm|^(php|js|pl|cgi|asp)\t/", $type)) {
			$typeid = 7;
		} elseif(preg_match("/text|^(txt|rtf|wri|chm)\t/", $type)) {
			$typeid = 6;
		} elseif(preg_match("/word|powerpoint|^(doc|ppt)\t/", $type)) {
			$typeid = 5;
		} elseif(preg_match("/^rar\t/", $type)) {
			$typeid = 4;
		} elseif(preg_match("/compressed|^(zip|arj|arc|cab|lzh|lha|tar|gz)\t/", $type)) {
			$typeid = 3;
		} elseif(preg_match("/octet-stream|^(exe|com|bat|dll)\t/", $type)) {
			$typeid = 2;
		} elseif($type) {
			$typeid = 1;
		} else {
			$typeid = 0;
		}
	}
	if($returnval == 'html') {
		return '<img src="images/attachicons/'.$attachicons[$typeid].'" border="0" class="absmiddle" alt="" />';
	} elseif($returnval == 'id') {
		return $typeid;
	}
}

function sizecount($filesize) {
	if($filesize >= 1073741824) {
		$filesize = round($filesize / 1073741824 * 100) / 100 . ' GB';
	} elseif($filesize >= 1048576) {
		$filesize = round($filesize / 1048576 * 100) / 100 . ' MB';
	} elseif($filesize >= 1024) {
		$filesize = round($filesize / 1024 * 100) / 100 . ' KB';
	} else {
		$filesize = $filesize . ' Bytes';
	}
	return $filesize;
}
/*
 * $attachpids 解析那些帖子
 * $attachtags pid   tid数组  匹配到[attach\](\d+)\[\/attach\]
 * $postlist 帖子列表
 * $showimages 帖子是否显示图片
 */
function parseattach($attachpids, $attachtags, &$postlist, $showimages = 1, $skipaids = array()) {
	global $db, $tablepre, $discuz_uid, $readaccess, $attachlist, $attachimgpost, $maxchargespan, $timestamp, $forum, $ftp, $attachurl, $dateformat, $timeformat, $timeoffset, $hideattach, $thread, $tradesaids, $trades, $exthtml, $tagstatus;

	$query = $db->query("SELECT a.*, ap.aid AS payed FROM {$tablepre}attachments a LEFT JOIN {$tablepre}attachpaymentlog ap 
    ON ap.aid=a.aid AND ap.uid='$discuz_uid' WHERE a.pid IN ($attachpids)");
	if($db->num_rows($query)) {
		while($attach = $db->fetch_array($query)) {
			$exthtml = '';
			if($skipaids && in_array($attach['aid'], $skipaids))
			{
				continue;
			}
			$attached = 0;
			$extension = strtolower(fileext($attach['filename']));
			$attach['attachicon'] = attachtype($extension."\t".$attach['filetype']);
			$attach['attachsize'] = sizecount($attach['filesize']);
            // settings 是否显示帖内图片   settings帖子中显示图片附件 在帖子中直接将图片或动画附件显示出来，而不需要点击附件链接
			$attach['attachimg'] = $showimages && $attachimgpost && $attach['isimage'] && (!$attach['readperm'] || $readaccess >= $attach['readperm']) ? 1 : 0;
			if($attach['price'])
			{
				if($maxchargespan && $timestamp - $attach['dateline'] >= $maxchargespan * 3600) //超过收费时间,不收费
				{
					$db->query("UPDATE {$tablepre}attachments SET price='0' WHERE aid='$attach[aid]'");
					$attach['price'] = 0;
				} else {
					if(!$discuz_uid || (!$forum['ismoderator'] && $attach['uid'] != $discuz_uid && !$attach['payed']))
					{
						$attach['unpayed'] = 1;
					}
				}
			}
			$attach['payed'] = $attach['payed'] || $forum['ismoderator'] || $attach['uid'] == $discuz_uid ? 1 : 0;
			$attach['url'] = $attach['remote'] ? $ftp['attachurl'] : $attachurl;
			$attach['dateline'] = gmdate("$dateformat $timeformat", $attach['dateline'] + $timeoffset * 3600);
			$postlist[$attach['pid']]['attachments'][$attach['aid']] = $attach;
			if(is_array($attachtags[$attach['pid']]) && in_array($attach['aid'], $attachtags[$attach['pid']]))
			{//	<strong>技巧提示:</strong> 您可以在帖子中使用 [attach]aid[/attach] 标签将附件显示于帖子内容的指定位置，而不按照默认方式排列在内容的尾部。点击 aid 数字可以在当前光标位置自动插入此代码。',

                $findattach[$attach['pid']][] = "/\[attach\]$attach[aid]\[\/attach\]/i";
                //$hideattach[$attach['pid']] 积分达到多少才能看,帖子积分不足,隐藏帖子包括附件
				$replaceattach[$attach['pid']][] = $hideattach[$attach['pid']] ? '[attach]***[/attach]' : attachtag($attach['pid'], $attach['aid'], $postlist);
				$attached = 1;
			}

			if(!$attached || $attach['unpayed'])
			{//$attached 上面没展示或未支付
				$postlist[$attach['pid']]['attachlist'] .= attachlist($attach);
			}
		}

		foreach($attachtags as $pid => $aids) {
			if($findattach[$pid]) {
				$postlist[$pid]['message'] = preg_replace($findattach[$pid], $replaceattach[$pid], $postlist[$pid]['message'], 1);
				$postlist[$pid]['message'] = preg_replace($findattach[$pid], '', $postlist[$pid]['message']);
			}
		}

	}
	else {
		$db->query("UPDATE {$tablepre}posts SET attachment='0' WHERE pid IN ($attachpids)", 'UNBUFFERED');
	}
}


function attachlist($attach) {
    global $attachrefcheck, $extcredits, $creditstrans, $ftp, $thumbstatus;
    $code="<dl class=\"t_attachlist\">";
    if($attach['attachimg'])
    {
        $code="<dt>
$attach[attachicon]
			<a href=\"attachment.php?aid=$attach[aid]&amp;nothumb=yes\" class=\"bold\" target=\"_blank\">$attach[filename]</a>
			<em>($attach[attachsize])</em>
		</dt>
		<dd>
			<p>
$attach[dateline]";
                if($attach['readperm'])
                    $code=", {lang readperm}: <strong>$attach[readperm]</strong>";

            if($attach['price'])
            {
                $code=", {lang price}: <strong>{$extcredits[$creditstrans][title]} $attach[price] {$extcredits[$creditstrans][unit]}</strong> &nbsp;
[<a href=\"misc.php?action=viewattachpayments&amp;aid=$attach[aid]\" target=\"_blank\">{lang pay_view}</a>]";
                if(!$attach['payed'])
                    $code="&nbsp;[<a href=\"misc.php?action=attachpay&amp;aid=$attach[aid]\" target=\"_blank\">{lang attachment_buy}</a>]";
            }
        if ($attach['description'])
            $code .= "<p>{$attach[description]}</p>";
        if( !$attach['price'] || $attach['payed'])
        {
            if($thumbstatus && $attach['thumb'])
            {
                if(($attachrefcheck || $attach['remote']) && !($attach['remote'] && substr($ftp['attachurl'], 0, 3) != 'ftp' && !$ftp['hideurl']))
                    $code.="<a href=\"#zoom\"><img onclick=\"zoom(this, 'attachment.php?aid=$attach[aid]&amp;noupdate=yes&amp;nothumb=yes')\" src=\"attachment.php?aid=$attach[aid]\" alt=\"$attach[filename]\" /></a>
";
                else
                    $code.="	<a href=\"#zoom\"><img onclick=\"zoom(this, '$attach[url]/$attach[attachment]')\" src=\"$attach[url]/$attach[attachment].thumb.jpg\" alt=\"$attach[filename]\" /></a>
			";
            }
            else
            {
                if(($attachrefcheck || $attach['remote']) && !($attach['remote'] && substr($ftp['attachurl'], 0, 3) != 'ftp' && !$ftp['hideurl']))
                    $code.="	<img src=\"attachment.php?aid=$attach[aid]&amp;noupdate=yes\" border=\"0\" onload=\"attachimg(this, 'load')\" onmouseover=\"attachimg(this, 'mouseover')\" onclick=\"zoom(this, 'attachment.php?aid=$attach[aid]')\" alt=\"$attach[filename]\" />
		";
                else
                    $code.="<img src=\"$attach[url]/$attach[attachment]\" onload=\"attachimg(this, 'load')\" onmouseover=\"attachimg(this, 'mouseover')\" onclick=\"zoom(this, '$attach[url]/$attach[attachment]')\" alt=\"$attach[filename]\" />
			";
            }
        }
        $code="</p>";

        $code="</dd>";
    }
    else
    {
        $code="<dt>
			$attach[attachicon]
			<a href=\"attachment.php?aid=$attach[aid]\" target=\"_blank\">$attach[filename]</a>
			<em>($attach[attachsize])</em>
		</dt>
		<dd>
			<p>
				$attach[dateline], {lang downloads}: $attach[downloads]";
        if($attach['readperm'])
        {
            $code=", {lang readperm}: <strong>$attach[readperm]</strong>";
            if($attach['price'])
            {
                $code=", {lang price}: <strong>{$extcredits[$creditstrans][title]} $attach[price] {$extcredits[$creditstrans][unit]}</strong> &nbsp;[<a href=\"misc.php?action=viewattachpayments&amp;aid=$attach[aid]\" target=\"_blank\">{lang pay_view}</a>]
			";
                if(!$attach['payed'])
                {
                    $code="&nbsp;[<a href=\"misc.php?action=attachpay&amp;aid=$attach[aid]\" target=\"_blank\">{lang attachment_buy}</a>]
	";
                }
            }
            if ($attach['description'])
                $code .= "<p>{$attach[description]}</p>";
        }
        $code="</dd>";
    }


    $code="</dl>";

    return $code;
}
?>